<template>
  <!-- 111 -->
  <!-- {{ options }} -->
  <!-- {{ props.item.page }} -->
  <el-select
    v-model="form[item.key]"
    :placeholder="placeholder"
    :loading="loading"
    :remote="!!item.remoteMethod"
    :remote-method="remoteMethod"
    :style="style"
    :multiple="item.multiple"
    :disabled="itemDisabled"
    :collapse-tags="item.collapseTags"
    @change="change"
    clearable
    filterable
  >
    <div v-infinite-scroll="loadNextPage" :infinite-scroll-immediate="false">
      <el-option
        v-for="{ itemText, itemValue, disabled, item } of option"
        :key="itemValue"
        :label="itemText"
        :item="item"
        :value="itemValue"
        :disabled="disabled"
      />
    </div>
  </el-select>
</template>

<script lang="ts">
import { defineComponent, PropType, ref, watch } from 'vue'
import { Option, Select } from '../types'
import { get, find, forEach, map } from 'lodash'
import usePlaceholder from '@/hooks/usePlacehoder'
import useSearch from '@/hooks/useSearch'
import * as api from '@/api/acceptances'
import { FormItemKey, ObjectType } from 'typings/interfaces'
import useDisabled from '../hooks/useDisabled'
import useFilterOption from '../hooks/useFilterOption'
import { getJSON } from 'js-cookie'

export default defineComponent({
  props: {
    item: {
      type: Object as PropType<Select>,
      required: true,
    },
    form: {
      type: Object as PropType<ObjectType>,
      required: true,
    },
    placeholderId: {
      type: String,
      default: 'lang.placeholder.select',
    },
    filterOptions: {
      type: Object as PropType<ObjectType>,
      default: () => ({}),
    },
    options: {
      type: Object as PropType<Record<FormItemKey, Option[]>>,
      required: true,
    },
    disabled: {
      type: Boolean,
      required: true,
    },
  },
  setup(props) {
    const placeholder = usePlaceholder(props.item, 'lang.placeholder.select')
    const itemDisabled = useDisabled(props.disabled, props.item.disabled)
    const key = get(props, 'item.alias') ?? get(props, 'item.key', '')
    const loading = ref(false)
    const { changePage, pagination, dataSource } = useSearch(props.item?.remoteMethod)
    const option = ref<Option[]>(get(props.options, [props.item.key], []))
    // 更新option
    watch(
      () => props.options[props.item.key],
      (state) => (option.value = state)
    )

    //筛选option
    if (props.item.linkage) {
      useFilterOption({
        option,
        dictMap: props.item.linkage.dictMap,
        primevalOption: get(props.options, [props.item.key], []),
        key: key,
        form: props.form,
        watchKey: props.item.linkage.key,
      })
    }

    watch(dataSource, (state) => {
      pagination.pageNum === 1
        ? (option.value = map(state, (item) => ({
            ...item,
            itemText: item[key],
            itemValue: item[key],
          })))
        : (option.value = [
            ...option.value,
            ...map(state, (item) => ({
              ...item,
              itemText: item[key],
              itemValue: item[key],
            })),
          ])
    })

    const remoteMethod = (value: string) => {
      loading.value = true
      changePage(1, { [props.item.key]: value })
        .then(() => (loading.value = false))
        .catch(() => (loading.value = false))
    }

    /* 加载下一页 */
    const loadNextPage = () => {
      const { pageNum, pageSize, total } = pagination
      if (pageNum * pageSize < total) {
        changePage(pageNum + 1, { [props.item.key]: props.form[props.item.key] })
      }
    }

    // 动态修改其他表单项
    const change = (value: string) => {
      const row = find(option.value, { itemValue: value })
      // alert()
      if (props.item.page === 'bridge') {
        props.form['routeAbbr'] = get(row, 'sectionAbbr')
        props.form['routeNo'] = get(row, 'routeNo')
        props.form['bridgeName'] = get(row, 'bridgeName')
        props.form['bridgeTypeCode'] = get(row, 'bridgeClassCode')
        props.form['bridgeStructureTypeCode'] = get(row, 'mainStructureTypeCode')
        props.form['centerStake'] = get(row, 'bridgeStake')
        props.form['operationCompanyName'] = get(row, 'operationCompanyName')
        props.form['fillUnit'] = localStorage.getItem('userInfo')
          ? JSON.parse(localStorage.getItem('userInfo') || '').units[0].name
          : null
        props.form['fillUnitId'] = localStorage.getItem('userInfo')
          ? JSON.parse(localStorage.getItem('userInfo') || '').units[0].id
          : null
        props.form['bridgeTechLevelCode'] =
          get(row, 'bdBridgeInEvaluation')[0].evaluationGradeCode || '暂无'
      } else if (props.item.page === 'culvert') {
        props.form['culvertNo'] = get(row, 'culvertNo')
        props.form['routeNo'] = get(row, 'routeNo')
        props.form['routeAbbr'] = get(row, 'sectionAbbr')
        props.form['administrativeDivision'] = get(row, 'regionName')
        props.form['culvertName'] = get(row, 'culvertName')
        props.form['maintenanceUnitName'] = localStorage.getItem('userInfo')
          ? JSON.parse(localStorage.getItem('userInfo') || '').units[0].id
          : null
        props.form['centerStake'] = get(row, 'centerStake')
        props.form['culvertTypeCode'] = get(row, 'culvertTypeCode')
      } else if (props.item.page === 'tunnel') {
        props.form['routeNo'] = get(row, 'routeNo')
        props.form['routeAbbr'] = get(row, 'sectionAbbr')
        props.form['tunnelName'] = get(row, 'tunnelName')
        props.form['maintenanceUnitName'] = localStorage.getItem('userInfo')
          ? JSON.parse(localStorage.getItem('userInfo') || '').units[0].id
          : null
        // props.form['culvertName'] = get(row, 'culvertName')
        // props.form['maintenanceUnitName'] = get(row, 'culvertNo') // 缺失
        // props.form['centerStake'] = get(row, 'centerStake')
        // props.form['culvertTypeCode'] = get(row, 'culvertTypeCode')
      } else if (props.item.page === 'slopeShield') {
        props.form['routeNo'] = get(row, 'routeNo')
        props.form['routeAbbr'] = get(row, 'sectionAbbr')
        props.form['maintenanceUnitName'] = localStorage.getItem('userInfo')
          ? JSON.parse(localStorage.getItem('userInfo') || '').units[0].id
          : null
        props.form['slopeStartStake'] = get(row, 'startStake')
        props.form['slopeEndStake'] = get(row, 'endStake')
        // props.form['slopeStartStake'] = get(row, 'startStake')
      } else if (props.item.page === 'task-list-distribute') {
        // console.log(111)
        props.form['mgtMaintenanceUnitName'] = get(row, 'operationCompanyName')
        // mgtMaintenanceUnitName
      } else if (props.item.page === 'daily-inspect') {
        // console.log(111)
        props.form['sectionNo'] = get(row, 'routNum')
        // mgtMaintenanceUnitName
      } else if (props.item.page === 'task-list-distribute2') {
        // console.log(111)
        props.form['routeAbbr'] = get(row, 'routeAbbr')
        props.form['centerStake'] = get(row, 'stake')
        props.form['routeNo'] = get(row, 'routeNo')
      } else if (props.item.page === 'task-list-distribute2') {
        // console.log(111)
        props.form['routeAbbr'] = get(row, 'routeAbbr')
        props.form['centerStake'] = get(row, 'stake')
        props.form['routeNo'] = get(row, 'routeNo')
      } else if (props.item.page === 'accept-apply-form') {
        // console.log(111)
        props.form['mgtMaintenanceUnitName'] = get(row, 'mgtMaintenanceUnitName')
        props.form['mgtMaintenanceUnitId'] = get(row, 'mgtMaintenanceUnitId')
        props.form['maintenanceUnitName'] = get(row, 'maintenanceUnitName')
        props.form['maintenanceUnitId'] = get(row, 'maintenanceUnitId')
        props.form['engineeringName'] = get(row, 'engineeringName')
        // props.form['engineeringName'] = get(row, 'engineeringName')
        props.form['routeAbbr'] = get(row, 'routeAbbr')
        // props.form['mgtMaintenanceUnitName'] = get(row, 'mgtMaintenanceUnitName')
        // props.form['mgtMaintenanceUnitId'] = get(row, 'mgtMaintenanceUnitId')
        // props.form['maintenanceUnitName'] = get(row, 'maintenanceUnitName')
        // props.form['maintenanceUnitId'] = get(row, 'maintenanceUnitId')
        // props.form['whetherDayworkCode'] = get(row, 'whetherDayworkCode')
        // props.form['acceptanceDate'] = get(row, 'acceptanceDate')
        api.innerQueryByMaintanceUnitTable(get(row, 'id')).then((res) => {
          console.log(res)
          props.form['repairAcceptApplyCompleteList'] = res.data.data.repairAcceptApplyCompleteList
        })
        // props.form['maintenanceUnitName'] = get(row, 'maintenanceUnitName')
        // props.form['maintenanceUnitId'] = get(row, 'maintenanceUnitId')
        // applicationDate
        // mgtMaintenanceUnitName
      } else {
        return null
      }
    }

    return {
      style: {
        width: props.item?.width ? props.item.width + 'px' : '100%',
      },
      option,
      loading,
      remoteMethod,
      placeholder,
      loadNextPage,
      change,
      itemDisabled,
    }
  },
})
</script>
